/***************************************************************************************************
 *Copyright(C),2010-2017,Sumscope
 *FileName	:  DictThreadGuard.h
 *Author	:  scofined.qi
 *Version	:  1.0
 *Date		:  2019/06/14
 *Desc		:  //用于主要说明此程序文件完成的主要功能
 *Relation :
 *Others	:  //其他内容说明
 *Function :  //主要函数列表，每条记录应包含函数名及功能简要说明
 *History	:
 * //修改历史记录列表，每条修改记录应包含修改日期、修改者及修改内容简介
 ***************************************************************************************************/
#pragma once

#include <core/sync/lock.h>

#ifdef WIN32
#include <process.h>
#include <windows.h>
#else
#include <errno.h>
#include <pthread.h>
#endif

class DictThreadGuard {
  enum {
    HARTBEAT_MAX = 4000,  //
    TIMEOUT_MAX = 7
  };
  enum kThreadClose {
    kThreadCloseRuning,     // 执行
    kThreadCloseNormal,     // 正常
    kThreadCloseKilled,     // 被杀掉==>自动重启
    kThreadCloseDeadLoop,   // 死循环==>断言弹窗
    kThreadCloseException,  // 异常  ==>生成dump
    kThreadCloseCount
  };
  typedef qb::base::CSLock CSLock;
#ifdef WIN32
  volatile DWORD m_thread_id;  // 当前要监控的字典线程
#else
  pthread_t m_thread_id;  // 当前要监控的字典线程
#endif

  volatile bool m_exiting;
  kThreadClose m_close_type;
  unsigned long m_last_tick;
  int m_timeout_count;
  int m_start_count;  // 字典线程启动次数,正常情况下为1
  CSLock m_lock;

 public:
  DictThreadGuard();
  static DictThreadGuard& Get() {
    static DictThreadGuard dh;
    return dh;
  }
  static const char* GetThreadCloseName(kThreadClose type);
  void StopCheck();
  void RunCheck();
#ifdef WIN32
  static void StaticRun(void*);
#else
  static void* StaticRun(void*);
#endif
  void OnStart();
  void OnEnd();
  void OnException();
  void OnHeartbeat(unsigned long now);

 protected:
  void CheckDeadLoop();
#ifdef WIN32
  DWORD GetThreadId();
  void SetThreadId(DWORD tid);
#else
  pthread_t GetThreadId();
  void SetThreadId(pthread_t tid);
#endif
};
